package http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

/**
 * HTTP客户程序
 * */
public class HTTPClient {
    String host;
    Socket socket;
    StringBuffer stringBuffer;

    public HTTPClient() throws IOException {
        this.socket = new Socket("localhost", 80);
        stringBuffer = new StringBuffer();
        host = "localhost";
    }

    public void request() throws IOException {
        stringBuffer.append("GET /index.jsp HTTP/1.1\r\n");
        stringBuffer.append("Host: ").append(host).append("\r\n");
        stringBuffer.append("Accept: */*\r\n");
        stringBuffer.append("Accept-Language: zh-cn\r\n");
        stringBuffer.append("Accept-Encoding: gzip, deflate\r\n");
        stringBuffer.append("User-Agent: HTTPClient\r\n");
        stringBuffer.append("Connection: Keep-Alive\r\n");

        // 发送HTTP请求
        OutputStream socketOut = socket.getOutputStream();
        socketOut.write(stringBuffer.toString().getBytes());
        socketOut.flush();

        // 接收响应结果
        InputStream socketIn = socket.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = socketIn.read(buf)) != -1)
            buffer.write(buf, 0, len);

        // 把字节数组转换为字符串
        System.out.println(Arrays.toString(buffer.toByteArray()));
//        System.out.println(new String(buffer.toByteArray()));
    }

    public static void main(String[] args) {
        try {
            new HTTPClient().request();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
